<template>
  <div class="purchase">
    <div class="purchase_header">
      <p>发起采购订单</p>
      <el-button @click="handelClickBack">返回</el-button>
    </div>
    <div class="purchase_supply_information">
      <p>供应商信息</p>
      <div class="purchase_supply_information_message">
        <div>
          <p>企业名称</p>
          <p>{{ detailObject?.orderDetailGroup?.length > 0 ? detailObject.orderDetailGroup[0].factorName : "" }}</p>
        </div>
        <div>
          <p>跟单人员</p>
          <p>{{ detailObject?.orderDetailGroup?.length > 0 ? detailObject.orderDetailGroup[0].trackerName : "" }}</p>
        </div>
        <div>
          <p>跟单人电话</p>
          <p>{{ detailObject?.orderDetailGroup?.length > 0 ? detailObject.orderDetailGroup[0].trackerTel : "" }}</p>
        </div>
        <div>
          <p>工厂地址</p>
          <p>{{ detailObject?.orderDetailGroup?.length > 0 ? detailObject.orderDetailGroup[0].factorAddress : "" }}</p>
        </div>
      </div>
    </div>
    <div class="purchase_commodity_information">
      <p>商品信息</p>
      <el-table
        :data="detailObject.orderDetailList"
        border
        style="width: 100%"
        @select="handelChange"
        @select-all="handelSelectAll"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="商品信息" width="480">
          <template #default="scope">
            <div class="sp_message">
              <div>
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div>
                <p>{{ scope.row.factorName }}</p>
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码:{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.businessSkuId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" /> -->
        <el-table-column prop="unitPrice" label="供应单价" />
        <el-table-column prop="commodityNum" label="数量" />
        <el-table-column prop="partNum" label="商品件数" />
        <el-table-column prop="" label="折扣率(%)">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.productInfos.discountRate"
              :controls="false"
              :min="0"
              :max="100"
              @input="handelInput"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="" label="折扣(元)">
          <template #default="scope">
            <el-input-number
              :min="0"
              :max="100"
              :controls="false"
              v-model="scope.row.productInfos.discountRatejg"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="采购实付价格"></el-table-column>
      </el-table>
    </div>
    <!-- 底部表单信息 -->
    <div class="purchase_form">
      <div class="purchase_form-left">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <div v-if="data.num == 2 || data.num == 3">
            <el-form-item label="定时采购时间" prop="">
              <el-date-picker
                v-model="detailObject.autoPurchaseTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="datetime"
                placeholder="日期"
                style="width: 100%"
              />
            </el-form-item>
          </div>
          <el-form-item label="收款账户选择" prop="">
            <el-input></el-input>
          </el-form-item>
          <el-form-item label="期望到货日期" prop="">
            <el-date-picker
              v-model="detailObject.expectedDeliveryTime"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="datetime"
              placeholder="日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="发货类型" prop="">
            <div style="width: 100%">
              <el-radio-group v-model="detailObject.receivingType">
                <el-radio :value="1">收货仓库</el-radio>
                <el-radio :value="2">直发客户</el-radio>
              </el-radio-group>
            </div>
            <div class="warehouse_content" v-if="detailObject.receivingType == 1">
              <el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库" @change="handelChangeWarehouse">
                <el-option
                  v-for="(item, index) in data.warehouseList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="其他费用" prop="">
            <el-input-number v-model="ruleForm.otherFee" style="width: 100%" :controls="false"></el-input-number>
          </el-form-item>
          <el-form-item label="优惠金额" prop="">
            <el-input-number v-model="ruleForm.discountAmount" style="width: 100%" :controls="false"></el-input-number>
          </el-form-item>
          <el-form-item label="订单说明" prop="">
            <el-input v-model="ruleForm.remark" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="">
            <el-upload
              v-model:file-list="FileList"
              action="https://dev.51jzt.com/dev-api/mall/tenant/merchant/order/excel/import"
              :headers="{
                Authorization: `Bearer ${getLocalCache(globalConfig.tokenAttr)}`
              }"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList);
                }
              "
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="purchase_form-right">
        <div class="purchase_form-right-top">
          <p>收货信息</p>
          <div>
            <p>姓名:</p>
            <!-- receiptInformation -->
            <p v-if="ruleForm.receivingType == 1 && ruleForm.warehouseId !== ''">{{ receiptInformation.receivingName }}</p>
            <p v-else><el-input v-model="detailObject.receivingName"></el-input></p>
          </div>
          <div>
            <p>电话:</p>
            <p v-if="ruleForm.receivingType == 1 && ruleForm.warehouseId !== ''">{{ receiptInformation.receivingMobile }}</p>
            <p v-else>
              <el-input v-model="detailObject.receivingMobile"></el-input>
            </p>
          </div>
          <div>
            <p>收货地址:</p>
            <p v-if="ruleForm.receivingType == 1 && ruleForm.warehouseId !== ''">{{ receiptInformation.receivingAddress }}</p>
            <div v-else>
              <el-cascader
                style="width: 100%"
                v-model="data.receivingAreaIds"
                :options="chinas"
                clearable
                @change="handelChnageCity"
              />
              <p>详细地址</p>
              <el-input v-model="detailObject.receivingAreaDetail"></el-input>
            </div>
          </div>
        </div>
        <div class="purchase_form-right-botton">
          <p>买家信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ detailObject.customerName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ detailObject.customerMobileCode }}</p>
          </div>
          <div>
            <p>项目地址:</p>
            <p>{{ detailObject.customerAddress }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="botton_btn">
      <div class="left">
        <p>
          优惠金额：-¥<span>{{ ruleForm.discountAmount }}</span>
        </p>
        <p>
          其他费用：¥<span>{{ ruleForm.otherFee }}</span>
        </p>
        <p>
          商品总价：¥<span>{{ data.totalPic }}</span>
        </p>
        <p>
          应付金额：<span
            >¥{{
              Number(data.totalPic) -
              Number(typeof ruleForm.discountAmount === "undefined" ? 0 : ruleForm.discountAmount) +
              Number(typeof ruleForm.otherFee === "undefined" ? 0 : ruleForm.otherFee)
            }}</span
          >
        </p>
      </div>
      <div class="right">
        <el-button type="primary" style="margin-left: 10px" v-if="data.num == 2" @click="handelClickClearTimer"
          >清除定时</el-button
        >
        <el-button type="" @click="handelClickBack">取消</el-button>
        <el-button type="primary" @click="handelClickCreatePurchase(data.num == 1 ? 1 : data.num == 2 ? 2 : 3)">
          {{ data.num == 1 ? "发起采购订单" : data.num == 2 ? "发起定时采购" : "确定定时采购设置" }}
        </el-button>
      </div>
    </div>
    <!-- 清除定时弹窗 -->
    <dialog-View :isShow="data.isShowClearTime" :width="'50%'">
      <div class="time_content">
        <el-icon size="50" color="red"><Warning /></el-icon>
        <p>您正在执行清除定时采购设置，清除后，此条定时采购计划将被请清除，需要手动进行发起采购，是否继续？</p>
      </div>
      <div class="clear_btn">
        <el-button @click="data.isShowClearTime = false">取消</el-button>
        <el-button type="primary" @click="onclickSbmitClear">确定</el-button>
      </div>
    </dialog-View>
    <dialog-View :isShow="data.isPurchaseOrder" :width="'50%'">
      <div class="procure_success">
        <div><img src="@/static/images/suceess.png" /></div>
        <div>您已成功将当前订单合同发起采购单，采购明细可前往采购单查看 ~</div>
        <div>
          <el-button @click="handelClickClose">关闭</el-button>
          <el-button type="primary" @click="handelClickGo">前往查看</el-button>
        </div>
      </div>
    </dialog-View>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getLocalCache } from "@/utils/cache";
import globalConfig from "@/settings";
import { Warning } from "@element-plus/icons-vue";
import china from "@/utils/china.json";
import {
  getOrderDetail,
  createPurchase,
  createTimingPurchase,
  delTimingPurchase,
  updateTimingPurchase
} from "@/apis/order/index";
import { getlistByTenantId } from "@/apis/procure/index";
import {
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { ElMessage } from "element-plus";
// 组件导入
import dialogView from "../components/dialogView.vue";
const useRout = useRouter();
const useRoutes = useRoute();
const detailObject = ref({});
const ruleFormRef = ref();
const ruleForm = ref({
  otherFee: 0,
  discountAmount: 0,
  warehouseId: ""
});
const rules = ref({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  ]
});
const data = reactive({
  orderId: "",
  num: 1, //1代表普通采购单，2代表定时采购单
  list: [
    { name: "sdsdsd1", mark: "mark", num: 20, jian: 30, zkl: "30%", zk: 20, pic: 999 },
    { name: "sdsdsd2", mark: "mark", num: 20, jian: 30, zkl: "30%", zk: 20, pic: 999 }
  ],
  totalPic: 0,
  // 清除定时
  isShowClearTime: false,
  // 清除定时-------end
  isPurchaseOrder: false,
  // 仓库数据
  warehouseList: [],
  warehouseCopyList: [],
  receivingAreaIds: []
  // 仓库数据-------end
});
const getDetail = id => {
  getOrderDetail(id)
    .then(res => {
      console.log(res);
      res.data.orderDetailList.map(it => {
        it.productInfos = {
          businessSkuId: it.businessSkuId,
          discountRate: "",
          remark: "",
          discountRatejg: ""
        };
      });
      detailObject.value = res.data;
      data.receivingAreaIds = res.data.receivingAreaIds.split(",");
      const sum = res.data.orderDetailList.reduce((accumulator, currentObject) => {
        return accumulator + (Number(currentObject.unitPrice) + Number(currentObject.salePrice)) * currentObject.commodityNum;
      }, 0);
      data.totalPic = sum;
    })
    .catch(err => {
      console.log(err);
    });
};
// 上传
const FileList = ref([]); //商品图片list
const uploadImg = ref();
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img" ? _fileList : [file]);
  if (!flag) {
    if (type === "img") {
      ElMessage({
        message: "只能上传图片文件",
        type: "error",
        offset: 60
      });
      const errorFile = _fileList.filter(item => !(item.raw.type === "image/jpeg" || item.raw.type === "image/png"));
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    return;
  }
  //   imgIsReady.value = false;
  if (type === "img") {
    FileList.value = fileList;

    for (let item of _fileList) {
      //   await customUpload(item, { file: item }, type);
    }
  } else {
    // videoList.value = fileList;
    // videoList.value = [file];
    // for (let item of videoList.value) {
    //   await customUpload(item, { file: item }, type);
    // }
  }
  console.log(FileList.value);
}, 100);
// 返回
const handelClickBack = () => {
  useRout.push({
    path: "/oder"
  });
};
// 多选框事件
const productInfos = ref([]);
const handelChange = item => {
  productInfos.value = item;
};
// 表格全选事件
const handelSelectAll = item => {
  productInfos.value = item;
};
// 发起采购订单
const handelClickCreatePurchase = n => {
  const { orderId } = detailObject.value;
  // const {receivingName} = detailObject.value;
  const { receivingType, warehouseId } = ruleForm.value;
  const { receivingName, receivingMobile, receivingAreaIds, receivingAreaDetail, receivingAddress } = receiptInformation.value;
  if (ruleForm.value.otherFee == null) {
    ruleForm.value.otherFee = 0;
  }
  if (ruleForm.value.discountAmount == null) {
    ruleForm.value.discountAmount = 0;
  }
  let receivingNames = ""; //收货姓名
  let receivingMobiles = ""; //收货电话
  let receivingAreaIdss = ""; //收货地址id
  let receivingAreaDetails = ""; //收货信息详细地址
  let receivingAddresss = ""; //收货地址
  if (warehouseId !== null && receivingType == 1) {
    console.log("changk");
    receivingNames = receivingName;
    receivingMobiles = receivingMobile;
    receivingAreaIdss = receivingAreaIds;
    receivingAreaDetails = receivingAreaDetail;
    receivingAddresss = receivingAddress;
  } else {
    console.log("zhifa");
    receivingNames = detailObject.value.receivingName;
    receivingMobiles = detailObject.value.receivingMobile;
    receivingAreaIdss = data.receivingAreaIds.join(",");
    receivingAreaDetails = detailObject.value.receivingAreaDetail;
    receivingAddresss = detailObject.value.receivingAddress;
  }
  // return;
  let obj = {
    orderId,
    productInfos: productInfos.value,
    receivingType,
    receivingWarehouseId: warehouseId,
    receivingName: receivingNames,
    receivingMobile: receivingMobiles,
    receivingAreaIds: receivingAreaIdss,
    receivingAreaDetail: receivingAreaDetails,
    receivingAddresss: receivingAddresss,
    expectedDeliveryTime: ruleForm.value.expectedDeliveryTime,
    otherFee: ruleForm.value.otherFee,
    discountAmount: ruleForm.value.discountAmount,
    remark: ruleForm.value.remark,
    autoPurchaseTime: ruleForm.value.autoPurchaseTime,
    attachmentFileUrls: ""
  };
  // let obj = {
  //   orderId,
  //   productInfos: productInfos.value,
  //   ...ruleForm.value
  // };
  if (n == 1) {
    // 创建采购
    createPurchase(obj)
      .then(res => {
        if (res.code === 200) {
          data.isPurchaseOrder = true;
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else if (n == 2) {
    // 创建定时采购
    createTimingPurchase(obj)
      .then(res => {
        if (res.code === 200) {
          data.isPurchaseOrder = true;
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else if (n == 3) {
    obj.purchaseOrderId = useRoutes.query.purchaseOrderId;
    // 编辑定时采购
    console.log(3);
    updateTimingPurchase(obj).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "编辑定时采购单成功",
          type: "success"
        });
        data.isPurchaseOrder = true;
      }
    });
  }
};
const handelInput = () => {
  console.log(detailObject.value);
};
// 清除时间回调函数
const handelClickClearTimer = () => {
  data.isShowClearTime = true;
  ruleForm.value.autoPurchaseTime = "";
};

const onclickSbmitClear = () => {
  delTimingPurchase({
    purchaseOrderId: useRoutes.query.purchaseOrderId
  }).then(() => {
    ElMessage({
      message: "清楚定时采购单成功",
      type: "success"
    });
    setTimeout(function () {
      useRout.push({
        path: "oder/detail"
      });
    }, 1000);
  });
};
// 前往采购单列表页
const handelClickGo = () => {
  useRout.push({
    path: "/procure/purchase-order"
  });
};
// 关闭
const handelClickClose = () => {
  data.isPurchaseOrder = false;
};
// 获取仓库信息
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    data.warehouseList = arr;
    data.warehouseCopyList = res.data;
  });
};
const receiptInformation = ref({});
const handelChangeWarehouse = v => {
  let obj = {};
  data.warehouseCopyList.map(it => {
    if (v == it.warehouseId) {
      console.log(it);
      obj.receivingName = it.manageUserName;
      obj.receivingMobile = it.managePhoneNo;
      obj.receivingAreaIds = it.provinceId + "," + it.cityId + "," + it.districtId;
      obj.receivingAreaDetail = it.address;
      obj.receivingAddress = it.address;
    }
  });
  receiptInformation.value = obj;
};
const handelChnageCity = v => {
  console.log(v);
};

const chinas = ref(china);
onMounted(() => {
  data.orderId = useRoutes.query.orderId;
  data.num = useRoutes.query.num;
  getDetail(data.orderId);
  getlistByTenantIds();
  // 初始化地址数据
  chinas.value.map(item => {
    // 第一层
    item.label = item.name;
    item.value = item.cityCode;
    // eslint-disable-next-line no-prototype-builtins
    if (item.hasOwnProperty("children")) {
      console.log("第二层");
      // 第二层
      item.children.map(citem => {
        citem.label = citem.name;
        citem.value = citem.cityCode;
        // eslint-disable-next-line no-prototype-builtins
        if (citem.hasOwnProperty("children")) {
          // 第三层
          citem.children.map(ccitem => {
            ccitem.label = ccitem.name;
            ccitem.value = ccitem.cityCode;
          });
        }
      });
    }
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
